/*
 * Copyright (C) 2009, 2010, B3log Team
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.b3log.nide.service;

import java.util.Arrays;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.ToolProvider;
import org.b3log.latke.Keys;
import org.b3log.latke.service.LangPropsService;
import org.b3log.latke.service.ServiceException;
import org.b3log.nide.model.source.java.JavaSourceFile;
import org.b3log.nide.model.source.java.JavaSourceObject;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Nide Java compiler.
 *
 * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
 * @version 1.0.0.3, Mar 10, 2011
 */
public final class NideJavaCompiler {

    /**
     * Logger.
     */
    private static final Logger LOGGER =
            Logger.getLogger(NideJavaCompiler.class.getName());
    /**
     * Default serial version uid.
     */
    private static final long serialVersionUID = 1L;
    /**
     * Language service.
     */
    private LangPropsService languageService;
    /**
     * Java compiler.
     */
    private final JavaCompiler compiler;

    /**
     * Public default constructor. Initializes {@linkplain #compiler}.
     */
    public NideJavaCompiler() {
        compiler = ToolProvider.getSystemJavaCompiler();

        if (null == compiler) {
            throw new RuntimeException("No Java compiler is provided!");
        }
    }

    /**
     * Compiles a single Java source file by the specified source file name,
     * source code and locale.
     *
     * @param fileName the specified source file name
     * @param javaSourceCode the specified source code
     * @param locale the specified locale
     * @return for example:
     * <pre>
     * {
     *     "sc": "COMPILE_SUCC",
     *     "msgs": [""]
     * }
     * </pre>, and another example:
     * <pre>
     * {
     *     "sc": "COMPILE_FAIL_",
     *     "msgs": [{
     *         "fileLineNum": 1,
     *         "javaCompilationErrMsg": "..."
     *     }, .... ]
     * }
     * </pre>
     * @throws ServiceException service exception
     */
    public JSONObject compile(final String fileName,
                              final String javaSourceCode,
                              final Locale locale)
            throws ServiceException {
        final JSONObject ret = new JSONObject();

        final DiagnosticCollector<JavaFileObject> diagnostics =
                new DiagnosticCollector<JavaFileObject>();
        final JavaFileObject file = new JavaSourceObject(fileName,
                                                         javaSourceCode);

        final Iterable<? extends JavaFileObject> compilationUnits =
                Arrays.asList(file);
        LOGGER.log(Level.FINE,
                   "Compiling source[fileName={0}, javaSourceCode={1}]",
                   new Object[]{fileName, javaSourceCode});
        final CompilationTask task = compiler.getTask(null, null,
                                                      diagnostics, null,
                                                      null,
                                                      compilationUnits);
        task.setLocale(locale);
        final boolean success = task.call();
        final JSONArray messages = new JSONArray();
        try {
            ret.put("msgs", messages);

            for (final Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.
                    getDiagnostics()) {
                final JSONObject message = new JSONObject();
                messages.put(message);

                message.put(JavaSourceFile.FILE_LINE_NUM,
                            diagnostic.getLineNumber());
                message.put(JavaSourceFile.JAVA_COMPILATION_ERROR_MSG,
                            diagnostic.getMessage(locale));
            }
        } catch (final JSONException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            throw new ServiceException(e);
        }

        try {

            if (success) {
                messages.put(languageService.get(Keys.LANGUAGE,
                                                 "compileFileSucc",
                                                 locale)); // XXX: i18n
                ret.put(Keys.STATUS_CODE, true);
            } else {
                ret.put(Keys.STATUS_CODE, false);
            }
        } catch (final JSONException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            throw new ServiceException(e);
        }

        return ret;
    }
}
